<template>
  <view class="page-container">
    
    <!-- 使用自定义导航栏组件 -->
    <nav-bar :title="'卡包管理'" />
    <view style="margin-top: 120rpx;"></view>
    <!-- 添加员工选择 -->
    <uni-forms-item label="销售员" name="staff_id" required>
      <view class="staff-container">
        <view v-for="staff in staffList" :key="staff.user_id" class="staff-item"
          :class="{ selected: this.staffId === staff.user_id }" @click="selectStaff(staff)">
          <text class="staff-name">{{ staff.name }}</text>
          <uni-icons :type="this.staffId === staff.user_id ? 'checkbox-filled' : 'checkbox'"
            :color="this.staffId === staff.user_id ? '#4cd964' : '#999'" size="20" />
        </view>
      </view>
    </uni-forms-item>
    <!-- 搜索工具栏 -->
    <view class="search-bar">
      <uni-search-bar v-model="searchName" placeholder="输入卡包名称" radius="100" clearButton="auto"
        @confirm="handleSearch" />
      <view class="action-buttons">
        <button class="search-btn" @click="handleSearch">搜索</button>
      </view>
    </view>

    <!-- 卡包列表 -->
    <view class="card-package-list" v-if="cardPackages.length">
      <view class="card-package-item" v-for="(item, index) in cardPackages" :key="index">
        <view class="card-package-info">
          <text class="card-package-name">{{ item.name }}</text>
          <view class="card-package-meta">
            <uni-tag :text="item.card_type === 'per_use' ? '次卡' : '综合卡'"
              :type="item.card_type === 'per_use' ? 'success' : 'warning'" size="small" />
            <text class="amount-text">
              充值: {{ item.recharge_amount || 0 }}元
            </text>
            <text class="amount-text">
              {{ item.card_type === 'per_use' ? '次数' : '赠送' }}:
              {{ item.card_type === 'per_use' ? item.total_amount : (item.gift_amount || 0) }}
              {{ item.card_type === 'per_use' ? '次' : '元' }}
            </text>
          </view>
          <view class="card-package-meta">
            <text class="amount-text">
              销售提成: {{ item.commission_rate * 100 || 0 }}%
            </text>
            <text class="amount-text">
              客户打折: {{ (item.is_owned ? item.son.discount_rate * 10 : item.discount_rate * 10).toFixed(1) || 0 }}折
            </text>

          </view>
          <text class="expiry-date" v-if="item.expiry_date">
            有效期至: {{ Util.formatDate(item.expiry_date) }}
          </text>
        </view>
        <view class="detail-link">
          <view class="detail-column">
            <button class="bind-btn" v-if="!item.is_owned"
              @click.stop="handleBindCardPackage(item.package_id)">绑定</button>
            <text v-else>已绑定</text>
            <text v-if="item.is_owned && item.bind_time" class="bind-time">
              ({{ item.bind_time }})
            </text>
          </view>
          <view class="detail-column" v-if="item.is_owned && item.card_type === 'default'">
            <button class="upgrade-btn" @click.stop="handleUpgrade(item.package_id, item.user_package_id)">充值升级</button>
          </view>
          <view class="detail-column" v-if="item.is_owned">
            <text class="amount-text">
              余额: {{ (item.son.remaining_amount).toFixed(1) || 0 }}{{ item.card_type === 'per_use' ? '次' : '元' }}
            </text>
          </view>

        </view>
      </view>
    </view>

    <view v-else class="empty-tip">
      <text>暂无卡包信息</text>
    </view>
  </view>
</template>

<script>
// 导入自定义导航栏组件
import NavBar from '@/components/nav-bar/nav-bar.vue'
import store from '@/utils/store.js'
import cardPackage from '@/utils/card_package.js';
import Util from '@/utils/util.js';
import user from '@/utils/user.js';

export default {
  data() {
    return {
      staffId: '',
      staffList: [], // 添加员工列表初始化
      Util,
      searchName: '',
      cardPackages: [],
      storeId: '',
      userId: ''
    };
  },
  onLoad(options) {
    this.storeId = options.store_id || '';
    this.userId = options.user_id || '';
    this.fetchCardPackages();
		this.loadStaffList(options.store_id);
    // 添加监听refreshCardPackageList事件
    uni.$on('refreshCardPackageList', this.fetchCardPackages);
  },
  onUnload() {
    // 移除事件监听
    uni.$off('refreshCardPackageList', this.fetchCardPackages);
  },
  methods: {
    selectStaff(staff) {
			this.staffId = staff.user_id;
		},
		async loadStaffList(storeId) {
			// 获取员工列表
			const staffResponse = await store.getStoreUsers(storeId, {
				'roles[]': ['staff', 'owner', 'manager'] // 修改为数组格式
			});
			this.staffList = staffResponse.list || []; // 修正数据结构访问
		},
    async fetchCardPackages() {
      try {
        const res = await user.getCardPackageList(this.userId, this.storeId, this.searchName);
        this.cardPackages = res;
      } catch (error) {
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    },
    handleSearch() {
      this.fetchCardPackages();
    },
    async handleBindCardPackage(packageId) {
      try {

        if (!this.staffId) {
          uni.showToast({
            title: '请先选择销售员',
            icon: 'none'
          });
          return;
        }
        await user.bindCardPackage(this.staffId,this.userId, this.storeId, packageId);
        uni.showToast({
          title: '绑定成功',
          icon: 'success'
        });
        this.fetchCardPackages(); // 刷新列表
      } catch (error) {
        uni.showToast({
          title: error.message || '绑定失败',
          icon: 'none'
        });
      }
    },
    handleUpgrade(packageId, user_package_id) {
      uni.navigateTo({
        url: `/pages/user/card_package_recharge?store_id=${this.storeId}&package_id=${packageId}&user_id=${this.userId}&user_package_id=${user_package_id}`
      });
    }
  }
}
</script>

<style lang="scss">
@import '@/uni.scss';

/* 卡包列表样式 */
.card-package-list {
  margin-top: 30rpx;
}

.card-package-item {
  background: #fff;
  border-radius: $uni-border-radius-lg;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.card-package-info {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
}

.card-package-name {
  font-size: 32rpx;
  font-weight: bold;
  color: $uni-main-color;
  margin-bottom: 10rpx;
}

.card-package-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.amount-text {
  font-size: 26rpx;
  color: $uni-text-color-grey;
}

.expiry-date {
  font-size: 26rpx;
  color: $uni-secondary-color;
}

.detail-link {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.bind-btn {
  background: $uni-primary;
  color: white;
  border-radius: $uni-border-radius-lg;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
}

.upgrade-btn {
  background: $uni-info;
  color: white;
  border-radius: $uni-border-radius-lg;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
}

.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
}

.bind-btn {
  margin-right: 20rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  background: #4cd964;
  color: #fff;
  border-radius: 25rpx;
  font-size: 26rpx;
}

.upgrade-btn {
  margin-right: 20rpx;
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  background: #007AFF;
  color: #fff;
  border-radius: 25rpx;
  font-size: 26rpx;
}

.detail-link {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 150rpx;
}

.detail-column {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10rpx;
}

.staff-container {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 15rpx;
	padding: 10rpx;
}

.staff-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 10rpx;
	background-color: #fff;
}

.staff-item.selected {
	background-color: #4cd964;
	border-color: #4cd964;
	color: white;
}

.staff-name {
	font-size: 28rpx;
	font-weight: bold;
	margin-bottom: 8rpx;
}

.staff-role {
	font-size: 24rpx;
	color: #666;
}

.staff-item.selected .staff-role {
	color: white;
}
</style>